//
//  DXBannerView.swift
//  SwiftDemo
//
//  Created by Steven on 2020/8/6.
//  Copyright © 2020 Steven. All rights reserved.
//

import UIKit

// 滚动方向
enum DXBannerScrollDirection : Int {
    case top
    case left
    case bottom
    case right
}

class DXBannerView: UIView {
    private let  colletionCell_id = "DXBannerViewCellId"
    var direction: DXBannerScrollDirection = .left

    var urls:[String] = [] {
        didSet{
            setupUI()
            if urls.count > 1{
                collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: scrollPosition, animated: false)//先计算一下滚动contentOffset
                startTimer()
            }
        }
    }

    let pageControl:UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.addTarget(self, action: #selector(didClickPageControl), for: UIControl.Event.valueChanged)
        pageControl.currentPage = 0;
        pageControl.pageIndicatorTintColor = .black
        pageControl.currentPageIndicatorTintColor = .red
        return pageControl
    }()
    lazy var collectionView:UICollectionView = {
        var layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection  = .horizontal
        
        let colletionV = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        colletionV.bounces = false
        colletionV.delegate = self
        colletionV.dataSource = self
        colletionV.isPagingEnabled = true
        colletionV.backgroundColor = .white
        colletionV.frame = self.bounds
        colletionV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: colletionCell_id)
        colletionV.showsHorizontalScrollIndicator = false;
        return colletionV
    }()
    lazy var contentOffset: CGFloat = {
        switch self.direction {
        case .left, .right:
            return  self.collectionView.contentOffset.x
            
        case .top, .bottom:
            return  self.collectionView.contentOffset.y
        }
    }()
    lazy var scrollPosition: UICollectionView.ScrollPosition = {
        switch direction {
        case .left:
            return UICollectionView.ScrollPosition.left
            
        case .right:
            return UICollectionView.ScrollPosition.right
            
        case .top:
            return UICollectionView.ScrollPosition.top
            
        case .bottom:
            return  UICollectionView.ScrollPosition.bottom
        }
    }()
    var datas:[String]? {
        var firstIndex = 0
        var secondIndex = 0
        var thirdIndex = 0
        switch urls.count {
        case 0:
            return []
        case 1:
            break
        default:
            //如果第0个,返回最后一个,否则前一个
            firstIndex = (currentIndex - 1) < 0 ? urls.count - 1 :currentIndex - 1
            secondIndex = currentIndex
            //最后一个 返回第0个, 否则 下一个
            thirdIndex  = (currentIndex + 1) > urls.count - 1 ? 0 : currentIndex + 1
        }
        return  [urls[firstIndex],urls[secondIndex],urls[thirdIndex]]
    }
    var currentIndex = 0{
        didSet{
//            DLog(currentIndex)
            self.pageControl.currentPage = self.currentIndex
        }
        willSet{
            
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI()  {
        self.addSubview(self.collectionView)
 
        
        self.addSubview(pageControl)
        pageControl.numberOfPages = urls.count
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.width.equalTo(200)
            make.bottom.equalTo(self).offset(-5)
            make.height.equalTo(30)
        }
      

    }
    @objc func didClickPageControl(sender:UIPageControl) -> Void {
//        self.currentIndex = sender.currentPage
      
 
    }
    func cancleTimer() -> Void {
        DXTimerManager.shared().cancleTimer(flag: "DXBannerView")

    }
    func startTimer() {
        DXTimerManager.shared().createTimer(flag: "DXBannerView", afterInterval: 2, interval: 2, repeats: true) { [weak self]() -> (Void) in
                  var item: Int = 0
                  switch self?.direction {
                    case .left, .bottom:
                        item = 2
                    case .top, .right:
                        item = 0
                  case .none:
                      break
                  }
                  DispatchQueue.main.async {
                      self?.collectionView.scrollToItem(at: IndexPath(item: item, section: 0), at: self!.scrollPosition, animated: true)

                  }
              }
    }
}

extension DXBannerView:UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate{
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        cancleTimer()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        startTimer()
    }

    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: colletionCell_id, for: indexPath)
        for subV in cell.subviews{
            subV.removeFromSuperview()
        }
        let imageV:UIImageView = {
            let imageV = UIImageView()
            cell.addSubview(imageV)
            imageV.snp.makeConstraints { (make) in
                make.edges.equalTo(cell)
            }
            return imageV
        }()
        let placeholderImage = UIImage(named: "icon_home_banner_default")
        let url = datas?[indexPath.item]

        if url != nil {
            imageV.kf.setImage(with: URL(string: url ?? ""),placeholder: placeholderImage)
//          imageV.kf.setImage(with: URL(string: url!), placeholder: placeholderImage, options: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageURL) in
//
//                imageV.image = image
//
//            })
        }
//        if urls![indexPath.item].hasPrefix("http") {
//                 defaultCell.imageView.kf.setImage(with: URL(string: datas![indexPath.item]), placeholder: placeholderImage)
//             } else {
//                 defaultCell.imageView.image = UIImage(named: datas![indexPath.item])
//             }
        

        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
            var offset: CGFloat = 0
            switch direction {
            case .left, .right:
                offset = scrollView.contentOffset.x
            case .top, .bottom:
                offset = scrollView.contentOffset.y
            }
            
            if offset >= contentOffset * 2 {
                
                if currentIndex == urls.count - 1 {//最后一个 返回首个
                    currentIndex = 0
                } else {
                    currentIndex += 1
                }
                collectionView.reloadData()
                collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: scrollPosition, animated: false)
            }
            
            if offset <= 0 {//向左
                if currentIndex == 0 {
                    currentIndex = urls.count - 1
                } else {
                    currentIndex -= 1
                }
                collectionView.reloadData()
                collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: scrollPosition, animated: false)
            }

    //        UIView.animate(withDuration: 0.3) {
    //
    //            self.pageControl.currentPage = self.index
    //        }
        }

}
